package com.hl.ruoyilkshop.config;

import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Elasticsearch索引初始化器
 * 应用启动时自动创建必要的索引
 */
@Component
public class ElasticsearchIndexInitializer implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchIndexInitializer.class);
    private static final String GOODS_INDEX = "goods1";

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void run(String... args) throws Exception {
        try {
            createGoodsIndexIfNotExists();
        } catch (Exception e) {
            logger.error("初始化Elasticsearch索引失败", e);
        }
    }

    /**
     * 创建商品索引（如果不存在）
     */
    private void createGoodsIndexIfNotExists() throws IOException {
        // 检查索引是否存在
        GetIndexRequest getIndexRequest = new GetIndexRequest();
        getIndexRequest.indices(GOODS_INDEX);
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        if (!exists) {
            logger.info("商品索引不存在，开始创建...");

            // 创建索引请求（不设置映射）
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(GOODS_INDEX);
            
            // 设置索引设置
            createIndexRequest.settings(Settings.builder()
                    .put("index.number_of_shards", 1)
                    .put("index.number_of_replicas", 0)
            );

            // 创建索引
            CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

            if (createIndexResponse.isAcknowledged()) {
                logger.info("商品索引创建成功");
                
                // 索引创建成功后，可以在这里添加映射（如果需要的话）
                // 由于我们使用动态映射，ES会自动推断字段类型
                logger.info("使用动态映射，字段类型将自动推断");
            } else {
                logger.error("商品索引创建失败");
            }
        } else {
            logger.info("商品索引已存在");
        }
    }

    /**
     * 删除商品索引（用于测试）
     */
    public void deleteGoodsIndex() throws IOException {
        GetIndexRequest getIndexRequest = new GetIndexRequest();
        getIndexRequest.indices(GOODS_INDEX);
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

        if (exists) {
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(GOODS_INDEX);
            client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            logger.info("商品索引已删除");
        }
    }
} 